package com.syni.mdd.sjb.community.base.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.syni.mdd.sjb.common.component.mybatis.common.entity.DxshAppUserInfo;
import com.syni.mdd.sjb.common.component.mybatis.common.mapper.DxshAppUserInfoMapper;
import com.syni.mdd.sjb.common.component.mybatis.community.entity.SjbQywxAdmin;
import com.syni.mdd.sjb.common.component.mybatis.community.entity.SjbQywxCompanyUser;
import com.syni.mdd.sjb.common.component.mybatis.community.mapper.SjbQxwxAdminMapper;
import com.syni.mdd.sjb.common.component.utils.common.utils.BeanUtils;
import com.syni.mdd.sjb.common.component.utils.common.utils.ResultMapHelper;
import com.syni.mdd.sjb.common.component.utils.common.utils.RpcResponseVo;
import com.syni.mdd.sjb.common.component.utils.feign.service.mdd.sjb.common.datatreasure.BankUserRestService;
import com.syni.mdd.sjb.common.component.utils.feign.service.mdd.sjb.common.datatreasure.DxshApiBusinessRestService;
import com.syni.mdd.sjb.common.component.utils.feign.service.mdd.sjb.common.datatreasure.DxshApiIndustryRestService;
import com.syni.mdd.sjb.common.component.utils.feign.service.mdd.sjb.common.datatreasure.dto.UserLoginDTO;
import com.syni.mdd.sjb.common.component.utils.feign.service.mdd.sjb.common.tool.VerificationCodeService;
import com.syni.mdd.sjb.common.component.utils.feign.service.mdd.sjb.common.tool.dto.CheckVerificationCodeDto;
import com.syni.mdd.sjb.community.base.auth.JwtTokenUtils;
import com.syni.mdd.sjb.community.base.config.QywxProperties;
import com.syni.mdd.sjb.community.base.constants.Constants;
import com.syni.mdd.sjb.community.base.constants.ResultCode;
import com.syni.mdd.sjb.community.base.constants.ResultMsg;
import com.syni.mdd.sjb.community.base.entity.bo.CompanyPermanentCodeBo;
import com.syni.mdd.sjb.community.base.entity.bo.LoginInfoBo;
import com.syni.mdd.sjb.community.base.entity.bo.SjbLoginBo;
import com.syni.mdd.sjb.community.base.entity.vo.BaseRqVo;
import com.syni.mdd.sjb.community.base.entity.vo.rp.BindSjbAccountRpVo;
import com.syni.mdd.sjb.community.base.entity.vo.rp.businessman.ManListRpVo;
import com.syni.mdd.sjb.community.base.entity.vo.rq.BindSjbAccountVo;
import com.syni.mdd.sjb.community.base.entity.vo.rq.ChooseIndustryVo;
import com.syni.mdd.sjb.community.base.service.SjbQywxAdminRoleRelationService;
import com.syni.mdd.sjb.community.base.service.SjbQywxAdminService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 数据宝管理员表 服务实现类
 * </p>
 *
 * @author lcc
 * @since 2021-02-23
 */
@Service
public class SjbQywxAdminServiceImpl extends ServiceImpl<SjbQxwxAdminMapper, SjbQywxAdmin> implements SjbQywxAdminService {
    @Autowired
    SjbQxwxAdminMapper sjbQxwxAdminMapper;

    @Autowired
    SjbQywxAdminRoleRelationService sjbQywxAdminRoleRelationService;

    @Autowired
    VerificationCodeService verificationCodeService;

    @Autowired
    BankUserRestService bankUserRestService;

    @Autowired
    JwtTokenUtils jwtTokenUtils;

    @Autowired
    DxshAppUserInfoMapper dxshAppUserInfoMapper;

    @Autowired
    QywxProperties qywxProperties;

    @Autowired
    DxshApiBusinessRestService dxshApiBusinessRestService;

    @Autowired
    DxshApiIndustryRestService dxshApiIndustryRestService;

    @Override
    public SjbQywxAdmin getByUserId(String userid) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("userid",userid);
        List<SjbQywxAdmin> sjbQywxAdmins = sjbQxwxAdminMapper.selectList(queryWrapper);
        if(CollectionUtils.isNotEmpty(sjbQywxAdmins)) {
            return sjbQywxAdmins.get(0);
        }
        return null;
    }

    @Override
    public SjbQywxAdmin getByCorpIdAndUserId(String corpId,String userid) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("userid",userid);
        queryWrapper.eq("corpid",corpId);
        List<SjbQywxAdmin> sjbQywxAdmins = sjbQxwxAdminMapper.selectList(queryWrapper);
        if(CollectionUtils.isNotEmpty(sjbQywxAdmins)) {
            return sjbQywxAdmins.get(0);
        }
        return null;
    }

    @Override
    @Transactional
    public SjbQywxAdmin syncAdminInformation(LoginInfoBo loginInfoBo) {
        String corpId = loginInfoBo.getCorp_info().getCorpid();
        String userid = loginInfoBo.getUser_info().getUserid();
        SjbQywxAdmin sjbQywxAdmin = getByCorpIdAndUserId(corpId,userid);
        if(sjbQywxAdmin == null){
            sjbQywxAdmin = new SjbQywxAdmin();
        }
        sjbQywxAdmin.setUserid(loginInfoBo.getUser_info().getUserid());
        sjbQywxAdmin.setOpenUserid(loginInfoBo.getUser_info().getOpen_userid());
        sjbQywxAdmin.setName(loginInfoBo.getUser_info().getName());
        sjbQywxAdmin.setAvatar(loginInfoBo.getUser_info().getAvatar());
        sjbQywxAdmin.setCorpid(loginInfoBo.getCorp_info().getCorpid());
        this.saveOrUpdate(sjbQywxAdmin);
        //同步至角色信息表
        sjbQywxAdminRoleRelationService.addCompanyAdminOrPlatformMan(corpId, sjbQywxAdmin.getId());
        return sjbQywxAdmin;
    }

    @Override
    @Transactional
    public void syncAdminInformation(CompanyPermanentCodeBo companyPermanentCodeBo) {
        SjbQywxAdmin sjbQywxAdmin = getByCorpIdAndUserId(companyPermanentCodeBo.getAuth_corp_info().getCorpid(),companyPermanentCodeBo.getAuth_user_info().getUserid());
        if(sjbQywxAdmin == null){
            sjbQywxAdmin = new SjbQywxAdmin();
        }
        sjbQywxAdmin.setUserid(companyPermanentCodeBo.getAuth_user_info().getUserid());
        sjbQywxAdmin.setOpenUserid(companyPermanentCodeBo.getAuth_user_info().getOpen_userid());
        sjbQywxAdmin.setName(companyPermanentCodeBo.getAuth_user_info().getName());
        sjbQywxAdmin.setAvatar(companyPermanentCodeBo.getAuth_user_info().getAvatar());
        sjbQywxAdmin.setCorpid(companyPermanentCodeBo.getAuth_corp_info().getCorpid());
        this.saveOrUpdate(sjbQywxAdmin);
        //同步至角色信息表
        sjbQywxAdminRoleRelationService.addCompanyAdminOrPlatformMan(companyPermanentCodeBo.getAuth_corp_info().getCorpid(),sjbQywxAdmin.getId());
    }

    @Override
    public SjbQywxAdmin getBySuperAdminByCorpId(String cropId) {
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("cropId",cropId);
        List<SjbQywxAdmin> sjbQywxAdmins = sjbQxwxAdminMapper.getBySuperAdminByCorpId(paramMap);
        if(CollectionUtils.isNotEmpty(sjbQywxAdmins)){
            return sjbQywxAdmins.get(0);
        }
        return null;
    }

    @Override
    public List<SjbQywxAdmin> getByAdminByCorpId(String cropId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(SjbQywxAdmin.CORPID,cropId);
        List<SjbQywxAdmin> sjbQywxAdmins = sjbQxwxAdminMapper.selectList(queryWrapper);
        if(CollectionUtils.isNotEmpty(sjbQywxAdmins)){
            return sjbQywxAdmins;
        }
        return null;
    }

    @Override
    public Map<String, Object> manList(BaseRqVo baseRqVo) {
        ManListRpVo manListRpVo = new ManListRpVo();
        Page iPage = new Page(baseRqVo.getPageNum(),baseRqVo.getPageSize());
        QueryWrapper queryWrapper = new QueryWrapper();
        SjbQywxAdmin superSjbQywxAdmin = getBySuperAdminByCorpId(baseRqVo.getCorpid());
        if(superSjbQywxAdmin != null){
            queryWrapper.ne(SjbQywxAdmin.ID,superSjbQywxAdmin.getId());
        }
        queryWrapper.eq(SjbQywxAdmin.CORPID,baseRqVo.getCorpid());
        Page<SjbQywxAdmin> sjbQywxAdminPage = sjbQxwxAdminMapper.selectPage(iPage,queryWrapper);
        manListRpVo.pageParamCal((int)sjbQywxAdminPage.getPages(),baseRqVo.getPageNum(),baseRqVo.getPageSize(),(int)sjbQywxAdminPage.getTotal());
        List<SjbQywxAdmin> sjbQywxAdmins = sjbQywxAdminPage.getRecords();
        if(CollectionUtils.isNotEmpty(sjbQywxAdmins)){
            for(SjbQywxAdmin sjbQywxAdmin : sjbQywxAdmins){
                ManListRpVo.AdminMan adminMan = new ManListRpVo.AdminMan();
                adminMan.setAdminId(sjbQywxAdmin.getId());
                adminMan.setName(sjbQywxAdmin.getName());
                adminMan.setAvatar(sjbQywxAdmin.getAvatar());
                adminMan.setDepartmentIds(sjbQywxAdmin.getDepartment());
                manListRpVo.getAdminMans().add(adminMan);
            }
        }
        return ResultMapHelper.success(manListRpVo);
    }

    @Override
    @Transactional
    public boolean addCompanyUserToAdmin(SjbQywxCompanyUser companyUser) {
        SjbQywxAdmin sjbQywxAdmin = new SjbQywxAdmin();
        BeanUtils.copyProperties(companyUser,sjbQywxAdmin);
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(SjbQywxAdmin.CORPID,companyUser.getCorpid());
        queryWrapper.eq(SjbQywxAdmin.USERID,companyUser.getUserid());
        List<SjbQywxAdmin> sjbQywxAdmins = sjbQxwxAdminMapper.selectList(queryWrapper);
        if(CollectionUtils.isNotEmpty(sjbQywxAdmins)){
            SjbQywxAdmin exist = sjbQywxAdmins.get(0);
            sjbQywxAdmin.setId(exist.getId());
            BeanUtils.copyProperties(sjbQywxAdmin,exist);
            sjbQxwxAdminMapper.updateById(sjbQywxAdmin);
        }else {
            sjbQxwxAdminMapper.insert(sjbQywxAdmin);

        }
        //添加一个角色
        sjbQywxAdminRoleRelationService.syncAdminRoleRelationInfomation(sjbQywxAdmin.getId(),Constants.QYWX_ADMIN_ROLE_PM);
        return true;
    }

    @Transactional
    public boolean addCompanyUserToAdmins(List<SjbQywxCompanyUser> companyUser) {
        if(CollectionUtils.isNotEmpty(companyUser)){
            for(SjbQywxCompanyUser sjbQywxCompanyUser : companyUser){
                addCompanyUserToAdmin(sjbQywxCompanyUser);
            }
        }
        return true;
    }

    @Override
    public boolean deleteAdmin(Integer adminId) {
        sjbQxwxAdminMapper.deleteById(adminId);
        return true;
    }

    @Override
    public Map<String, Object> bindSjbAccount(BindSjbAccountVo bindSjbAccountVo) {
        //校验验证码
        CheckVerificationCodeDto checkVerificationCodeDto = new CheckVerificationCodeDto();
        checkVerificationCodeDto.setPhone(bindSjbAccountVo.getPhone());
        checkVerificationCodeDto.setCodeType(Constants.BIND_PHONE_10);
        checkVerificationCodeDto.setVerificationCode(bindSjbAccountVo.getVerificationCode());
        Map<String,Object> result = verificationCodeService.checkVerificationCode(checkVerificationCodeDto);
        if(!ResultMapHelper.isSuccess(result)){
            return ResultMapHelper.result(ResultCode.CODE_ERROR_100, ResultMsg.HAND_FAIL);
        }
        Map<String,Object> data = (Map<String, Object>) result.get("data");
        if(!(data.containsKey("result") && data.get("result").toString().equals("1"))){
            return ResultMapHelper.result(ResultCode.CODE_ERROR_100, ResultMsg.MSG_VER_CODE_ERROR);
        }
        //查询当前手机号是否绑定其他账号
        if(this.checkPhoneIsBind(bindSjbAccountVo.getPhone(),bindSjbAccountVo.getQxwxAdminId())){
            return ResultMapHelper.result(ResultCode.CODE_ERROR_100, ResultMsg.MSG_ACCOUNT_PHONE_IS_BIND);
        }
        //注册为数据宝用户
        UserLoginDTO userLoginDTO = new UserLoginDTO();
        userLoginDTO.setLoginWay(Constants.LOGIN_WAY_PWD);
        userLoginDTO.setPhone(bindSjbAccountVo.getPhone());
        userLoginDTO.setPassword(qywxProperties.getUserSjbLoginSuperpwd());
        Map<String,Object> loginData = bankUserRestService.login(userLoginDTO);
        if(!ResultMapHelper.isSuccess(loginData)){
            return ResultMapHelper.result(ResultCode.CODE_ERROR_100, loginData.get("msg").toString());
        }
        //绑定数据
        SjbLoginBo sjbLoginBo = JSON.parseObject(JSON.toJSONString(loginData.get("data")),SjbLoginBo.class);
        Map<String,Object> userData = JSON.parseObject(jwtTokenUtils.verifyToken(sjbLoginBo.getToken()));
        SjbQywxAdmin sjbQywxAdmin = this.getById(bindSjbAccountVo.getQxwxAdminId());
        if(sjbQywxAdmin == null){
            return ResultMapHelper.result(ResultCode.CODE_PC_NO_LOGIN, ResultMsg.MSG_PC_TOKEN_FAIL);
        }
        sjbQywxAdmin.setPhone(userData.get("phone").toString());
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(DxshAppUserInfo.USER_ID,Integer.parseInt(userData.get("userId").toString()));
        DxshAppUserInfo dxshAppUserInfo = null;
        List<DxshAppUserInfo> dxshAppUserInfos = dxshAppUserInfoMapper.selectList(queryWrapper);
        if(CollectionUtils.isNotEmpty(dxshAppUserInfos)){
            dxshAppUserInfo = dxshAppUserInfos.get(0);
            sjbQywxAdmin.setSjbUserId(dxshAppUserInfo.getId());

        }
        sjbQxwxAdminMapper.updateById(sjbQywxAdmin);
        BindSjbAccountRpVo bindSjbAccountRpVo = new BindSjbAccountRpVo();
        //bindSjbAccountRpVo.setToken(sjbLoginBo.getToken());
        return ResultMapHelper.success(bindSjbAccountRpVo);
    }

    @Override
    public boolean checkPhoneIsBind(String phone, Integer qxwxAdminId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(SjbQywxAdmin.PHONE,phone);
        List<SjbQywxAdmin> sjbQywxAdmins = sjbQxwxAdminMapper.selectList(queryWrapper);
        if(CollectionUtils.isNotEmpty(sjbQywxAdmins)){
            SjbQywxAdmin sjbQywxAdmin = sjbQywxAdmins.get(0);
            if(!sjbQywxAdmin.getId().equals(qxwxAdminId)){
                return true;
            }
        }
        return false;
    }

    @Override
    public Map<String, Object> chooseIndustry(ChooseIndustryVo chooseIndustryVo) {
        Map<String,Object> ret = dxshApiBusinessRestService.userChooseIndustryByIndustryId(chooseIndustryVo.getUserId(),chooseIndustryVo.getIndustryId());
        if(ResultMapHelper.isSuccess(ret)){
            return ResultMapHelper.success(ResultMsg.HAND_SUCCESS);
        }
        return ResultMapHelper.result(ResultCode.CODE_ERROR_100,ret.get("msg").toString());
    }

    @Override
    public Map<String, Object> getAllIndustry() {
        RpcResponseVo rpcResponseVo = dxshApiIndustryRestService.getAllIndustry();
        if(rpcResponseVo.isSuccess()){
            return ResultMapHelper.success(rpcResponseVo.getData());
        }
        return ResultMapHelper.result(ResultCode.CODE_ERROR_100,rpcResponseVo.getMsg());
    }
}
